package edu.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import edu.domain.Goods;
import edu.service.GoodsService;
import edu.support.base.BasePage;
import edu.support.base.controller.AdminBaseController;
import edu.support.mybatis.MybatisWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import static edu.config.ConstantConfig.CATEGORY_LIST;

/**
 * (Goods)表控制层
 *
 * @date 2022-02-09 20:31:21
 */

@Controller
@RequestMapping("/admin/goods")
public class GoodsAdminController extends AdminBaseController {

    @Autowired
    private GoodsService goodsService;

    /**
     * 列表
     *
     * @param model
     * @param goods
     * @return
     */
    @RequestMapping("list")
    public String list(Model model, Goods goods, BasePage rowPage) {
        QueryWrapper<Goods> wrapper = new MybatisWrapper<Goods>()
                .like("name", goods.getName())
                .orderByDesc("create_time");
        PageInfo<Goods> pageInfo = goodsService.page(rowPage, wrapper);
        setModelAttribute(model, pageInfo);
        return "admin/goods/list";
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping("delete/{id}")
    public String del(@PathVariable Long id, RedirectAttributes attributes) {
        goodsService.removeById(id);
        return redirect("/admin/goods/list", "删除成功", attributes);
    }


    /**
     * 详情
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("detail/{id}")
    public String detail(@PathVariable Long id, Model model) {
        Goods goods = goodsService.getById(id);
        if (null == goods) {
            goods = new Goods();
        }
        model.addAttribute("goods", goods);
        model.addAttribute("CATEGORY_LIST", CATEGORY_LIST);
        return "admin/goods/detail";
    }

    /**
     * 更新
     *
     * @param goods
     * @return
     */
    @RequestMapping("update")
    public String update(Goods goods, RedirectAttributes attributes, MultipartFile file) {
        if(file!=null && !file.isEmpty()){
            String path = saveFile(file);
            goods.setPath(path);
        }
        goodsService.saveOrUpdate(goods);
        return redirect("/admin/goods/list", "操作成功", attributes);
    }

}


